package com.szq.netty.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;

/**
 * @ClassName: NettyClient
 * @Description:
 * @Author: szq
 * @Date: 2021-11-11 09:06:53
 */
public class NettyClient {

    public static void main(String[] args) {
        new NettyClient().bind(7397);
    }

    private void bind(int port) {
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(workerGroup);
            b.channel(NioDatagramChannel.class);
            b.handler(new MyChannelInitializer());

            Channel channel = b.bind(9378).sync().channel();
            //向目标端口发送数据
            System.out.println("netty-demo-111 client start done.");
            channel.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer("你好端口7397的bugstack虫洞栈，我是客户端小爱，你在吗！", Charset.forName("GBK")),
                    new InetSocketAddress("192.168.30.32", port))).sync();
            channel.closeFuture().await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            workerGroup.shutdownGracefully();
        }
    }
}
